﻿CREATE TRIGGER [tr_ObjectStatus_Insert]
ON [dbo].[t_ObjectStatus] 
FOR INSERT
AS

IF NOT @@ROWCOUNT BETWEEN 1 AND 1000 RETURN

DECLARE cur CURSOR LOCAL FOR
SELECT ObjectName,Key_1, FromID, ToID FROM inserted 

OPEN cur

DECLARE @ObjectName sysname,@Key_1 sysname,@FromID int,@ToID int
FETCH NEXT FROM cur INTO @ObjectName,@Key_1,@FromID,@ToID

WHILE @@FETCH_STATUS = 0 BEGIN
	--PRINT dbo.sprint5('@ObjectName:%s,@Key_1:%s,@FromID:%s,@ToID:%s,IsWorkFlowSystem:%s',@ObjectName,@Key_1,@FromID,@ToID,dbo.Context_IsWorkFlowSystem())
	IF @ToID > 0 AND NOT EXISTS(SELECT * FROM t_Menu m INNER JOIN t_Menu mp ON m.ParentMenuID = mp.MenuID WHERE mp.Params = @ObjectName AND m.MenuID = @ToID) BEGIN	RAISERROR('Status %d does not belond to object %s.',16,1,@ToID,@ObjectName)	ROLLBACK TRAN RETURN END
	IF dbo.fs_Workflow_Check(@FromID,@ToID) = 0 BEGIN
		DECLARE @SF sysname,@ST sysname,@UN sysname,@GR nvarchar(512)
		SELECT @SF = MenuName FROM t_Menu WHERE MenuID = @FromID
		SELECT @ST = MenuName,@UN = dbo.UserName() FROM t_Menu WHERE MenuID = @ToID
		EXEC sp__Join 'SELECT GroupName FROM UserGroups()',',',@GR OUTPUT
		ROLLBACK TRAN
		RAISERROR('There is no path from [%s(%d)] to [%s(%d)] for %s/%s.',16,1,@SF,@FromID,@ST,@ToID,@GR,@UN)
		RETURN
	END
	EXEC smenu__Action @Key_1,@FromID,@ToID
	IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END
	FETCH NEXT FROM cur INTO @ObjectName,@Key_1,@FromID,@ToID
END

RETURN


